using System;
using System.Data;
using System.Reflection;
using FastReflectionLib;

namespace HF.Repository
{
    public class TypeConverter
    {
        public static Converter<T, TU> UpCast<T, TU>()
            where T : TU
            where TU : class
        {
            return item => item as TU;
        }
    }

    [Serializable]
    public class ReadonlyRepositoryModel
    {
        public string GetCacheKey()
        {
            return this.GetType().Name + this.GetKeyValue();
        }

        public new ReadonlyRepositoryModel MemberwiseClone()
        {
            return base.MemberwiseClone() as ReadonlyRepositoryModel;
        }
    }

    [Serializable]
    public class RepositoryModel : ReadonlyRepositoryModel
    {
        public void Delete()
        {
            Delete(null);
        }

        public void Delete(IDbTransaction transaction)
        {
            var rep = RepositoryFactory.Create(GetType()) as IRepository;

            rep.Delete(this, transaction);
        }

        public void CreateOrUpdate()
        {
            CreateOrUpdate(null);
        }

        public void CreateOrUpdate(IDbTransaction transaction)
        {
            var rep = RepositoryFactory.Create(GetType()) as IRepository;
            rep.CreateOrUpdate(this, transaction);
        }
    }
}